package components.ball;

import images.GameImagesMap;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.GameComponent;
import com.uqbar.vainilla.appearances.Sprite;
import components.CollisionableComponent;

public class NormalBall extends CollisionableComponent {

	private GameComponent startOn;
	private BallState state;
	private int speed;
	private int dirVectorX;
	private int dirVectorY;
	
	public NormalBall(double possX, double possY, GameComponent startComponent){
		super(20, 20, possX, possY);
		this.setStartOn(startComponent);

		Sprite sp = GameImagesMap.getImage("normalball");
		this.setAppearance(sp);
		this.speed = 100;
		this.dirVectorX = 1;
		this.dirVectorY = -2;
		this.state = new StartBallState(this, startComponent);
	}
	
	
	public int getSpeed() {
		return speed;
	}


	public void setSpeed(int speed) {
		this.speed = speed;
	}


	public int getDirVectorX() {
		return dirVectorX;
	}


	public void setDirVectorX(int dirVectorX) {
		this.dirVectorX = dirVectorX;
	}


	public int getDirVectorY() {
		return dirVectorY;
	}


	public void setDirVectorY(int dirVectorY) {
		this.dirVectorY = dirVectorY;
	}



	@Override
	public boolean isSolid() {
		return false;
	}


	@Override
	protected void onCollisionWithSolid(CollisionableComponent gc) {
		this.bounce(gc);
	}

	private void bounce(CollisionableComponent gc) {
		double gcx, gcy, bx, by;
		gcx = gc.getX();
		gcy = gc.getY();
		bx = this.getX();
		by = this.getY();
		if (gcx >= bx){
			if (this.getDiameter() +bx > gcx){
				this.updateDirection(1, -1);
			}
			else {
				this.updateDirection(-1, 1);
			}
		}
		else {
			if (gcy < by){
				if (gcx + gc.getDiameter() > bx){
					this.updateDirection(1, -1);
				}
				else{
					this.updateDirection(-1, 1);	
				}
				
			}
			else{
				if (this.getHeight() + by > gcy){
					this.updateDirection(-1, 1);
				}
				else {
					this.updateDirection(1, -1);	
				}
			}
		}
	}
	
	public void updateDirection(int xScale, int yScale){
		this.setDirVectorX(this.dirVectorX * xScale);
		this.setDirVectorY(this.dirVectorY * yScale);
	}
	
	@Override
	protected void defineCollide(CollisionableComponent gc) {
		gc.collideWithBall(this);
	}


	public void setState(BallState state) {
		this.state = state;
	}


	public BallState getState() {
		return state;
	}


	public void restart() {

		
	}


	@Override
	protected void effectiveUpdate(DeltaState deltaState) {
		this.getState().update(deltaState);
	}


	public void setStartOn(GameComponent startOn) {
		this.startOn = startOn;
	}


	public GameComponent getStartOn() {
		return startOn;
	}
	
}
